﻿#include <time.h>
#include <pcap.h>
#include <winsock2.h>

#include "catch.h"
#include "bindings.h"

int start(cnd_t *cnd, int interactive, uint16_t src_port)
{
	pcap_if_t *alldevs;
	pcap_if_t *d;

	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	u_int netmask;

	// todo：使用 snprintf 和 strncat 兼容非win平台
	char port_str[6];
	sprintf_s(port_str, sizeof(port_str), "%d", src_port);
	char packet_filter[20] = "dst port ";
	strcat_s(packet_filter, sizeof(packet_filter), port_str);
	// printf("%s\n", packet_filter);

	struct bpf_program fcode;
	pcap_dumper_t *dumpfile;

	/* Retrieve the device list */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	char *default_dev_name;
	None_or_String name = find_default_dev_name();
	if (name.tag == None_String)
	{
		printf("No device name found!\n");
		default_dev_name = NULL;
	}
	else if (name.tag == Some_String)
	{
		printf("device name: %s\n", name.some);
		default_dev_name = name.some;
	}

	int i = 0;
	/* choose the device */
	for (d = alldevs; d; d = d->next)
	{
		// printf("%d. %s\n", ++i, d->name);
		char *result = strstr(d->name, default_dev_name);
		if (result != NULL)
		{
			printf("find device!\n");
			i = 1;
			break;
		}
	}

	if (i == 0)
	{
		printf("\nNo interfaces found! Make sure Npcap is installed.\n");
		return -1;
	}

	/* Open the adapter */
	if ((adhandle = pcap_open(d->name,					 // name of the device
							  65536,					 // portion of the packet to capture.
														 // 65536 grants that the whole packet will be captured on all the MACs.
							  PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
							  1000,						 // read timeout
							  NULL,						 // remote authentication
							  errbuf					 // error buffer
							  )) == NULL)
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by Npcap\n", d->name);
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* Check the link layer. We support only Ethernet for simplicity. */
	if (pcap_datalink(adhandle) != DLT_EN10MB)
	{
		fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	if (d->addresses != NULL)
		/* Retrieve the mask of the first address of the interface */
		netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	else
		/* If the interface is without addresses we suppose to be in a C class network */
		netmask = 0xffffff;

	// compile the filter
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0)
	{
		fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	// set the filter
	if (pcap_setfilter(adhandle, &fcode) < 0)
	{
		fprintf(stderr, "\nError setting the filter.\n");
		/* Free the device list */
		pcap_freealldevs(alldevs);
		return -1;
	}

	// 文件保存
	dumpfile = pcap_dump_open(adhandle, "save.pcap");
	if (dumpfile == NULL)
	{
		fprintf(stderr, "\nError opening output file\n");
		return -1;
	}

	printf("\nlistening on %s...\n", d->description);

	/* At this point, we don't need any more the device list. Free it */
	pcap_freealldevs(alldevs);

	/* start the capture */
	// pcap_loop(adhandle, -1, packet_handler, (unsigned char *)dumpfile);

	// 通知主线程抓包已启动
	cnd_signal(cnd);

	/* start the capture */
	if (interactive)
	{
		pcap_loop(adhandle, -1, packet_handler, (unsigned char *)dumpfile);
	}
	else
	{
		pcap_loop(adhandle, 1, packet_handler, (unsigned char *)dumpfile);
	}
	pcap_close(adhandle);

	return 0;
}

/* Callback function invoked by libpcap for every incoming packet */
void packet_handler(uint8_t *param, const struct pcap_pkthdr *header, const uint8_t *pkt_data)
{
	struct tm ltime;
	char timestr[16];
	ip_header *ih;
	udp_header *uh;
	dns_header *dh;
	dns_answer *da;
	uint32_t ip_len;
	uint16_t sport, dport;
	time_t local_tv_sec;
	int lenOfDomainName = 1;

	const uint8_t *p = pkt_data;

	/*
	 * Unused variable
	 */
	(VOID)(param);

	/* convert the timestamp to readable format */
	local_tv_sec = header->ts.tv_sec;
	localtime_s(&ltime, &local_tv_sec);
	strftime(timestr, sizeof timestr, "%H:%M:%S", &ltime);

	/* print timestamp and length of the packet */
	printf("总长度:%d \n", header->len);

	/* retireve the position of the ip header */
	ih = (ip_header *)(pkt_data +
					   14); // length of ethernet header

	/* retireve the position of the udp header */
	ip_len = (ih->ver_ihl & 0xf) * 4;
	uh = (udp_header *)((uint8_t *)ih + ip_len);
	dh = (dns_header *)((uint8_t *)uh + 8);

	int i;
	uint8_t *p2 = ((uint8_t *)dh + 12);
	while (*p2 != 0x00)
	{
		for (i = 0; i <= *p2; i++)
		{
			p2++;
			lenOfDomainName++;
		}
	}

	da = (dns_answer *)((uint8_t *)dh + 12 + lenOfDomainName + 4);

	/* convert from network byte order to host byte order */
	sport = ntohs(uh->sport);
	dport = ntohs(uh->dport);

	// printf("packet_handler*********************\n");
	// printf("%d\n", dh->T_ID);

	/* print ip addresses and udp ports */
	printf("源地址：%d.%d.%d.%d\n源端口号：%d\n目的地址：%d.%d.%d.%d\n目的端口号：%d\n",
		   ih->saddr.byte1,
		   ih->saddr.byte2,
		   ih->saddr.byte3,
		   ih->saddr.byte4,
		   sport,
		   ih->daddr.byte1,
		   ih->daddr.byte2,
		   ih->daddr.byte3,
		   ih->daddr.byte4,
		   dport);
	printf("回答数：%d\n", ntohs(dh->Answer_RRs));
	for (i = 1; i <= ntohs(dh->Answer_RRs); i++)
	{
		printf("回答%d：%d.%d.%d.%d\n",
			   i,
			   da->addr.byte1,
			   da->addr.byte2,
			   da->addr.byte3,
			   da->addr.byte4);
		da = (dns_answer *)((uint8_t *)da + 16);
	}
	pcap_dump(param, header, pkt_data);
	printf("\n> ");
}
